package Server

import (
	"context"
	"time"

	hypernexusApp "github.com/wzh200x/hyperNexus/hyperNexusApp"
	"github.com/wzh200x/hyperNexus/hyperNexusProtocol/cacheServerProtocol"
)

// cacheServerOperateImp servant implementation
type cacheServerOperateImp struct {
}

// Init servant init
func (imp *cacheServerOperateImp) Init() error {

	return nil
}

// Destroy servant destroy
func (imp *cacheServerOperateImp) Destroy() {
	// 清理资源
}

// Set 设置缓存
func (imp *cacheServerOperateImp) Set(ctx context.Context, req cacheServerProtocol.CacheSetRequest) (out cacheServerProtocol.CacheSetResponse, err error) {

	// 设置过期时间
	expiration := time.Duration(req.Expiration) * time.Second
	if req.Expiration == 0 {
		expiration = 0 // 0表示永不过期
	}

	// 调用缓存管理器设置缓存
	err = ServerApp.CacheManager.Set(hypernexusApp.GHyperNexusApp.ProjectName+"_"+req.Key, req.Value, expiration)
	if err != nil {
		out.Success = false
		out.Message = err.Error()
		return out, err
	}

	out.Success = true
	out.Message = ""
	return out, nil
}

// Get 获取缓存
func (imp *cacheServerOperateImp) Get(ctx context.Context, req cacheServerProtocol.CacheGetRequest) (out cacheServerProtocol.CacheGetResponse, err error) {

	// 调用缓存管理器获取缓存
	value, err := ServerApp.CacheManager.Get(hypernexusApp.GHyperNexusApp.ProjectName + "_" + req.Key)
	if err != nil {
		out.Exists = false
		out.Message = err.Error()
		return out, err
	}
	if value.Val() == nil {
		out.Exists = false
		out.Message = "key not exists"
		return out, nil
	}
	out.Exists = true
	out.Value = value.Bytes()
	return out, nil
}

// Delete 删除缓存
func (imp *cacheServerOperateImp) Delete(ctx context.Context, req cacheServerProtocol.CacheDeleteRequest) (out cacheServerProtocol.CacheDeleteResponse, err error) {

	// 调用缓存管理器删除缓存
	_, err = ServerApp.CacheManager.Remove(hypernexusApp.GHyperNexusApp.ProjectName + "_" + req.Key)
	if err != nil {
		out.Success = false
		out.Message = err.Error()
		return out, err
	}

	out.Success = true
	out.Message = ""
	return out, nil
}
